import globalStore from "@/stores/modules/global";
export default function websocketPrintHook() {
  const router = useRouter();
  const global = globalStore();
  const messages = ref<(string | ArrayBuffer)[]>([]);
  const inputMessage = ref({ command: "scan", resolution: 200, duplex: 0 });
  // 初始化 WebSocket 连接
  const initWebSocket = () => {
    let socket = new WebSocket("ws://127.0.0.1:18596/");
    // 监听连接成功
    socket.addEventListener("open", (event) => {
      if (socket && socket.readyState === WebSocket.OPEN) {
        messages.value = [];
        socket.send(JSON.stringify(inputMessage.value));
      } else {
        console.error("WebSocket 未连接");
      }
    });

    // 监听接收消息
    socket.addEventListener("message", (msg) => {
      if (typeof msg.data == "string") {
        if (JSON.parse(msg.data).ErrCode === 0) {
          ElMessage.success("资料扫描完成");
          setTimeout(() => {
            // 成功
            global.activeIndex = 2; // ocr扫描到接口，看看是初次认定还是非初次认定。
            ElMessage.success("OCR识别成功");
            setTimeout(() => {
              global.activeIndex = 3;
              global.firstCheckState = false;
            }, 4000);
          }, 4000);
        } else {
          ElMessage.error(JSON.stringify(JSON.parse(msg.data).ErrMessage));
          // 失败
          global.currentId = "";
          router.push({ name: "home" });
          global.activeIndex = 0;
        }
      } else {
        var reader = new FileReader();
        reader.onload = (msg) => {
          if (msg.target?.readyState == FileReader.DONE) {
            let url = msg.target.result;
            let arr = [];
            if (url) {
              arr.push(url);
            }
            messages.value = arr;
          }
        };
        reader.readAsDataURL(msg.data);
      }
    });

    // 监听错误
    socket.addEventListener("error", (event) => {
      console.error("WebSocket 错误:", event);
    });

    // 监听连接关闭
    socket.addEventListener("close", (event) => {
      console.log("WebSocket 连接关闭:", event);
    });
  };
  return {
    // 暴露触发扫码事件、结果信息。
    initWebSocket,
    messages,
  };
}
